import axios from "axios";
import {ElMessage} from "element-plus";
import {ref} from "vue";
import {useUserStore} from "../stores/modules/userStore";
import pinia from "../stores";

let request = axios.create({
    baseURL: '/api',
    //baseURL: ref(import.meta.env.VITE_APP_BASE_URL),
    timeout: 5000,
    headers:{
        'Content-Type': 'application/json;charset=UTF-8',
    }
})

request.interceptors.request.use((config) => {
    config.headers['Access-Control-Allow-Origin'] = '*';
//    config.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    let userStore = useUserStore(pinia);
    console.log("request.interceptors.request.use is called,userStore:",userStore.token);
    if (userStore.token) {
        config.headers.token = userStore.token;
    }
    //console.log("request.interceptors.request.use,config:",config);
    return config;
})

request.interceptors.response.use((response) => {
    // ElMessage({
    //     type: "200",
    //     message: response.data
    // });
    return response.data;
}, (error) => {
    let message = '';
    let status = error.response.status;
    switch (status) {
        case 401:
            message = "token过期";
            break;
        case 403:
            message = "无权访问";
            break;
        case 404:
            message = "请求地址错误";
            break;
        case 500:
            break;
        default:
            message = "网路出现问题";
            break;
    }
    ElMessage({
        type: "error",
        message: message,
    });

    return Promise.reject(error);
    // return error;//都可以，不报错

})
export default request;
